package com.junzhiit.nengji.cms.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.junzhiit.nengji.bo.FullReductionConditionBO;
import com.junzhiit.nengji.cms.service.FullReductionConditionService;
import com.junzhiit.nengji.cms.web.exception.FullReductionConditionException;
import com.junzhiit.nengji.cms.web.vo.ResultVO;
import com.junzhiit.nengji.dao.FullReductionConditionDAO;
import com.junzhiit.nengji.model.FullReductionCondition;

@Service
public class FullReductionConditionServiceImpl implements FullReductionConditionService {

	@Autowired
	FullReductionConditionDAO fullReductionConditionDAO;

	@Override
	public ResultVO delete(String id) {
		ResultVO result = new ResultVO();
		FullReductionCondition fullReductionCondition = fullReductionConditionDAO.query(id);
		if (fullReductionCondition == null) {
			throw new FullReductionConditionException("满减优惠门槛信息不存在");
		}
		String fullReductionId = fullReductionCondition.getFullReductionId();
		Boolean rlt = fullReductionConditionDAO.delete(id);
		if (rlt) {
			List<FullReductionConditionBO> fullReductionConditionBOList = fullReductionConditionDAO.findByFullReductionId(fullReductionId);
			List<FullReductionCondition> fullReductionConditionList = new ArrayList<>();
			for (FullReductionConditionBO fullReductionConditionBO : fullReductionConditionBOList) {
				if (fullReductionConditionBO.getLevel() > fullReductionCondition.getLevel()) {
					fullReductionConditionBO.setLevel(fullReductionConditionBO.getLevel() - 1);
					FullReductionCondition fullReductionConditionObj = new FullReductionCondition();
					BeanUtils.copyProperties(fullReductionConditionBO, fullReductionConditionObj);
					fullReductionConditionList.add(fullReductionConditionObj);
				}
			}
			if (!fullReductionConditionList.isEmpty()) {
				fullReductionConditionDAO.batchUpdate(fullReductionConditionList);
			}
		}
		return result;
	}
}
